package at.codebase.web.servlets.api;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import at.codebase.core.search.ItemSearch;
import at.codebase.core.search.ItemSearchResult;
import at.codebase.core.search.ItemSearchResultInfo;
import at.codebase.security.SecurityUtils;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters;
import at.codebase.web.util.URLParameters.ParameterException;
import at.codebase.web.util.servlet.ApiSecureServlet;

import com.google.appengine.api.search.SearchQueryException;

public class SearchSuggestionsAPIServlet extends ApiSecureServlet {

	private static int MAX_RESULTS = 10;
	
	@SuppressWarnings("unchecked")
	@Override
	protected JSONObject processRequest(RequestInformation requestInfo, String authToken) {
		
		JSONObject result = successResult();
		JSONArray suggestions = new JSONArray();
		
		URLParameters parameters = requestInfo.getParameters();
		
		try {
			String query = parameters.getString("query");
			
			query = "titleSubstrings:"+SecurityUtils.sanatizeSearchQuery(query);

			ItemSearchResultInfo resultList = null;
			try {
				resultList = ItemSearch.search(query, MAX_RESULTS, 0);
				
				for (ItemSearchResult itemResult : resultList.getResults()) {
					JSONObject suggestionResult = new JSONObject();
					suggestionResult.put("itemId", itemResult.getItem().getId().toString());
					suggestionResult.put("fullString",
							SecurityUtils.sanatize(itemResult.getItem().getTitle()));
					if (!(requestInfo.isUserLoggedIn() && itemResult.getItem().getId().equals(requestInfo.getUser().getId())))
						
						suggestions.add(suggestionResult);
				}
				
			} catch (SearchQueryException ex) { }
		} catch (ParameterException e) { }
		
		result.put("items", suggestions);
		return result;
		
	}

}
